package main

import (
	"fmt"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/storage"
	"fyne.io/fyne/v2/storage/repository"
	"gitee.com/y2h/fyneExplorer/me"
)

func (f *fileDialog) refreshDir(dir fyne.ListableURI) {
	f.dataLock.Lock()
	f.data = nil
	f.dataLock.Unlock()

	files, err := dir.List()
	if err != nil {
		fyne.LogError("Unable to read ListableURI "+dir.String(), err)
		return
	}

	var icons []fyne.URI
	parent, err := storage.Parent(dir)
	if err != nil && err != repository.ErrURIRoot {
		fyne.LogError("Unable to get parent of "+dir.String(), err)
		return
	}
	if parent != nil && parent.String() != dir.String() {
		icons = append(icons, parent)
	}

	me.NumF = 0
	me.NumFd = 0
	me.NumH = 0
	me.Total = len(files)
	for _, file := range files {
		if isHidden(file) {
			me.NumH++
		}
		if !f.showHidden && isHidden(file) {
			continue
		}

		listable, err := storage.ListerForURI(file)
		if err == nil { // URI points to a directory
			me.NumFd++
			if me.FilterType == "All" || me.FilterType == "只显示文件夹" {
				icons = append(icons, listable)
			}
			// } else if f.file.filter == nil || f.file.filter.Matches(file) {
		} else {
			if me.FilterType == "All" ||
				me.FilterType == "只显示文件" ||
				(me.FilterType != "只显示文件夹" &&
					f.filter.Matches(file)) {
				icons = append(icons, file)
			}
			me.NumF++
		}
	}
	if len(icons) > 0 && icons[0] == parent {
		me.Sort(icons[1:], me.SortFn)
		// icons = icons[:numfd+1]
	} else {
		me.Sort(icons, me.SortFn)
		// icons = icons[:numfd]
	}
	f.dataLock.Lock()
	f.data = icons
	f.dataLock.Unlock()

	me.CvsNum.Text = fmt.Sprintf("%2d项，%2d文件夹，%2d文件,%2d项隐藏",
		me.Total, me.NumFd, me.NumF, me.NumH)
	me.CvsNum.Refresh()

	f.files.Refresh()
	f.filesScroll.Offset = fyne.NewPos(0, 0)
	f.filesScroll.Refresh()
}
